package cn.thoughtworks.school.programCenter.services;

import cn.thoughtworks.school.programCenter.entities.User;
import cn.thoughtworks.school.programCenter.entities.dto.UserDto;
import cn.thoughtworks.school.programCenter.exceptions.BusinessException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserExcelImportService {

    private Workbook workbook;
    private Sheet firstSheet;

    public void init(MultipartFile file) throws IOException, BusinessException {
        this.workbook = this.getWorkbook(file);
        this.firstSheet = this.getFirstSheet(workbook);
    }

    private Sheet getFirstSheet(Workbook workbook) throws BusinessException {
        Sheet sheet = workbook.getSheetAt(0);
        if (Objects.isNull(sheet)) {
            throw new BusinessException("Could not find the first sheet");
        }
        return sheet;
    }

    private Workbook getWorkbook(MultipartFile file) throws IOException {
        Workbook workbook;
        String fileName = file.getOriginalFilename();
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();

        if (isExcel2003) {
            workbook = new HSSFWorkbook(is);
        } else {
            workbook = new XSSFWorkbook(is);
        }
        return workbook;
    }

    @Transactional
    public List<UserDto> parseUsers(User current) {
        List<UserDto> result = new ArrayList();
        for (int i = 1; i <= firstSheet.getLastRowNum(); ++i) {
            Row row = firstSheet.getRow(i);
            result.add(parseUser(row,current.getId()));
        }
        return result;
    }

    private UserDto parseUser(Row row,Long creatorId) {
        String userName = getStringCell(row,0);
        String email = getStringCell(row,1);
        String password = getStringCell(row,2);
        return UserDto.build(userName, password, email,creatorId);
    }

    private String getStringCell(Row row, int index) {
        Cell cell = row.getCell(index);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }
}
